package com.zt.securityTest.filter;

import com.alibaba.fastjson.JSON;
import com.zt.securityTest.entity.LoginUser;
import com.zt.securityTest.exception.CustomerAuthenticationException;
import com.zt.securityTest.handler.LoginFailureHandler;
import com.zt.securityTest.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * time: 2024.11.16
 * 自定义jwt过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private LoginFailureHandler loginFailureHandler;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String TOKEN_KEY = "token:key:";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            String uri = request.getRequestURI();
            //如果是访问登录接口则不需要进行拦截，直接放行
            if (!uri.equals("/users/login")){
                this.validateToken(request);
            }
        } catch (AuthenticationException e) {
            loginFailureHandler.onAuthenticationFailure(request,response,e);
        }
        filterChain.doFilter(request,response);
    }

    //用于token的校验
    private void validateToken(HttpServletRequest request) {
        //获取token
        String token = request.getHeader("Authorization");
        //如果token不存在(第一次：从header中查找)
        if (!StringUtils.hasText(token)){
            token = request.getParameter("Authorization");
        }
        //如果token不存在(第二次：从Parameter中查找)
        if (!StringUtils.hasText(token)){
            throw new CustomerAuthenticationException("token为空");
        }

        String token_value = redisTemplate.opsForValue().get(TOKEN_KEY+token);
        if (!StringUtils.hasText(token_value)){
            throw new CustomerAuthenticationException("token过期,请重新登录");
        }
    
        LoginUser loginUser = null;

        //token存在，进行校验
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String loginUserString = claims.getSubject();
            loginUser = JSON.parseObject(loginUserString, LoginUser.class);
        } catch (Exception e) {
            throw new CustomerAuthenticationException("token校验失败");
        }

        //将查询出来的信息放入securityContextHolder中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //重置过期时间
        redisTemplate.opsForValue().set(TOKEN_KEY+token,token,5, TimeUnit.MINUTES);
    }
}
